package todo;


import se.lth.cs.realtime.*;
import done.AbstractWashingMachine;


public class SpinController extends PeriodicThread {
	AbstractWashingMachine mach;
	double speed;
	int activeMode;
	long timeStart;
	double timeElapsed;
	int nextDirection;
	boolean spinLeft;

	public SpinController(AbstractWashingMachine mach, double speed) {
		super((long) (10000/speed));
		this.mach = mach;
		this.speed = speed;
	}

	public void perform() {
		SpinEvent msg = (SpinEvent) mailbox.tryFetch();
		if(msg != null){
			activeMode = msg.getMode();
			switch(activeMode){
			case SpinEvent.SPIN_FAST: 
				mach.setSpin(AbstractWashingMachine.SPIN_FAST);
				break;
			case SpinEvent.SPIN_SLOW: 
				mach.setSpin(AbstractWashingMachine.SPIN_LEFT);
				timeStart = System.currentTimeMillis();
				spinLeft = true;
				System.out.println("Spin on");
				break;
			case SpinEvent.SPIN_OFF:
				mach.setSpin(AbstractWashingMachine.SPIN_OFF);
				System.out.println("Spin off");
				break;
			}
		}
		
		
		// EJ KLAR
		System.out.println((System.currentTimeMillis()-timeStart)/speed + " --- " + 60*1000/speed);
		if(activeMode == SpinEvent.SPIN_SLOW){
			if((System.currentTimeMillis()-timeStart)/speed >= 60*1000/speed){
				timeStart = System.currentTimeMillis();
				if(spinLeft){
					mach.setSpin(AbstractWashingMachine.SPIN_RIGHT);
				}else{
					mach.setSpin(AbstractWashingMachine.SPIN_LEFT);
				}
				spinLeft = !spinLeft;
			}
		}
	}
}
